package com.lnking.lnkingplace.Util;


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExportImage {

    public static void  exporExcel(XSSFWorkbook workbook,HttpServletResponse response){
        OutputStream out = null;
        try {
            String codedFileName = URLEncoder.encode("tt" + ".xlsx", "UTF-8");
            response.setContentType("application/octet-stream");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-disposition", "attachment;filename=" + codedFileName);
            out = response.getOutputStream();
            workbook.write(out);
        } catch (Exception var16) {
            var16.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }
    }

    public static void exportHeadlessFastener(String header, String body,HttpServletResponse response) throws Exception {
        // 将数据放入map类型的集合中
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

        //接收页面参数
//        RequestModel<HeadlessFastenerQueryParam> requestModel = RequestUtil.getRequestModel(header, body, HeadlessFastenerQueryParam.class);
//        requestModel.getBody().setPage(1);
//        requestModel.getBody().setPageCount(100000);
//        PageResult<HeadlessFastenerQueryResult> res = headlessFastenerService.queryHeadlessFastener(requestModel.getBody());
//        List<HeadlessFastenerQueryResult> list = res.getList();

        //设置表头
        String[] assetHeadTemp = {
                "图片1",
                "图片2"
        };

        String[] assetNameTemp = {
                "imageUrl1",
                "imageUrl2"
        };

        //将数据填充到map中
        Map<String,Object> hashMap = new LinkedHashMap<String, Object>();
        hashMap.put("imageUrl1", "http://10.205.20.203:8001/enclosures/d164a85b6a884fafaecd7a6357ac6af0.jpg");
        hashMap.put("imageUrl2", "http://10.205.20.203:8001/enclosures/727d03d195a14b20a94ebedc5246ccb4.png");
        dataList.add(hashMap);

        XSSFWorkbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");
        Row row;
        Cell cell;
        // 图片字节数组
        byte[] imgByte = null;

        // excel样式
        CellStyle style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);// 水平
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直

        // 输出表头
        row = sheet.createRow(0);
        for (int i = 0; i < assetHeadTemp.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(assetHeadTemp[i]);
            cell.setCellStyle(style);
        }
        // 输出内容
        int rowIndex = 1;
        for (Map<String, Object> map : dataList) {
            row = sheet.createRow(rowIndex++);
            // 设置行高
            row.setHeightInPoints((short) 70);

            for (int i = 0; i < assetNameTemp.length; i++) {
                cell = row.createCell(i);
                // 设置列宽
                sheet.setColumnWidth(i, 256 * 25);
                // 输出图片到第1列 到 第六列
                if (i >= 0 && i <= 5) {
                    imgByte = null;
                    if(map.get(assetNameTemp[i]) == null){
                        continue;
                    }
                    // 输出图片
                    URL url = new URL(map.get(assetNameTemp[i]).toString());
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    //设置超时间为3秒
                    conn.setConnectTimeout(3*1000);
                    //防止屏蔽程序抓取而返回403错误
                    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

                    //得到输入流
                    InputStream inputStream = conn.getInputStream();
                    // 图片转化为字节数组
                    imgByte = IOUtils.toByteArray(inputStream);
                    if (imgByte != null) {
                        // 图片存在即输出图片
                        int addPicture = wb.addPicture(imgByte, wb.PICTURE_TYPE_PNG);
                        Drawing drawing = sheet.createDrawingPatriarch();
                        CreationHelper helper = wb.getCreationHelper();
                        ClientAnchor anchor = helper.createClientAnchor();

                        anchor.setRow1(rowIndex - 1);
                        anchor.setCol1(i);

                        // 指定我想要的长宽
                        double standardWidth = 150;
                        double standardHeight = 100;

                        // 计算单元格的长宽


//                        double cellWidth = sheet.getColumnWidthInPixels(cell.getColumnIndex());
                        double cellWidth = sheet.getColumnWidth(cell.getColumnIndex());
                        double cellHeight = cell.getRow().getHeightInPoints() / 72 * 96;

                        // 计算需要的长宽比例的系数
                        double a = standardWidth / cellWidth;
                        double b = standardHeight / cellHeight;

                        Picture picture = drawing.createPicture(anchor, addPicture);
                        picture.resize(5);
                    }
                } else {
                    // 输出文字
                    Object object = map.get(assetNameTemp[i]);

                    if(i == 15 || i == 17 || i == 19 || i == 23){
                        String dateString = null;
                        if(object != null){
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                            dateString = sdf.format((Date)object);
                        }
                        cell.setCellValue(
                                dateString != null ? dateString : "");
						/*CellStyle style2 = wb.createCellStyle();
						XSSFDataFormat createDataFormat = wb.createDataFormat();
						style2.setDataFormat(createDataFormat.getFormat("yyyy-MM-dd HH:mm:ss"));
						cell.setCellStyle(style2);*/
                    }else{
                        cell.setCellValue(object != null ? object.toString() : "");
                    }
                    cell.setCellStyle(style);
                }
            }
        }
        exporExcel(wb, response);
    }


    /**
     * 说明：生成Excel格式为xlsx
     * 参数：input为输入文件路径
     * 返回值：输出文件路径，文件名随机生成
     */
    public void setImgXlsx(String input) throws IOException {
        BufferedImage bufferImg = null;
        try {
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            bufferImg = ImageIO.read(new File("D:/Backgroud Image/1130148RqIM.jpg"));
            ImageIO.write(bufferImg, "jpg", byteArrayOut);
            XSSFWorkbook wb = new XSSFWorkbook();
            XSSFSheet sheet = wb.getSheet("Sheet1");
            if (sheet == null) {
                sheet = wb.createSheet("Sheet1");
            }
            //画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
            Drawing drawing = sheet.createDrawingPatriarch();
            //anchor主要用于设置图片的属性
            //修改前四个参数用于设置边距（暂不清楚原理）
            XSSFClientAnchor anchor = new XSSFClientAnchor(100000, 100000, -100000, -100000, 6, 10, 7, 11);
            anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);
            //插入图片
            Picture picture = drawing.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
//            picture.resize();
            // 写入excel文件

            System.out.println("----Excle文件已生成------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
